package demo;
import java.util.Comparator;
import java.util.PriorityQueue;
public class Solution {
    //自定义最大堆的比较方法
    static class RerseverComparator implements Comparator<Integer> {
        @Override
        public int compare(Integer o1,Integer o2){
            return o2-o1;
        }
    }
    public int[] smallestK(int[] arr, int k) {
        if(k==0){
            return new int[0];
        }
        RerseverComparator c = new RerseverComparator();
        PriorityQueue<Integer> pq = new PriorityQueue<>(c);
        for(int i=0;i<k;i++){
            pq.offer(arr[i]);
        }
        for(int i=k;i<arr.length;i++){
            int top=pq.peek();
            if(arr[i]<top){
                pq.poll();
                pq.offer(arr[i]);
            }
        }
        int[]ans=new int[k];
        for(int i=0;i<k;i++){
            ans[i]=pq.poll();
        }
        return ans;
    }
}
